#!/usr/bin/python
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""PREP

Prepares a checkout for building and testing the Clang + Bionic toolchain.

"""

import argparse
import fnmatch
import os
import stat
import shutil
import StringIO
import sys

sys.path.append('tools')

from bionic_dirs import *
from file_update import Mkdir, Rmdir, Symlink
from file_update import NeedsUpdate, UpdateFromTo, UpdateText
import process


def BuildPNaCl(options):
  tc_args = ['python', 'toolchain_build_pnacl.py',
             '--install', os.path.join(options.output, 'bionic_work')]

  if options.no_cache:
    tc_args += ['--no-use-cached-results', '--no-use-remote-cache']

  if True or options.sync:
    tc_args += ['-y']
  
  print 'Building PNaCl: ' + ' '.join(tc_args)
  process.Run(tc_args, cwd=TOOLCHAIN_BUILD_DIR, outfile=sys.stdout)


def BuildSCons(options):
  scons_args = ['./scons', '--mode=nacl,dbg-linux', '-j20']
  for arch in ['arm', 'x86_64', 'x86_32']:
    platform = 'platform=' + arch
    irt = 'scons-out/nacl_irt-%s/staging/irt_core.nexe' % arch.replace('_', '-')
    bootstrap = 'nacl_helper_bootstrap'
    print 'Building SCons: ' + arch
    process.Run(scons_args + [platform, 'sel_ldr', irt, bootstrap],
              cwd=NATIVE_CLIENT_DIR, outfile=sys.stdout)


def GetLibunwind():
  libunwind = os.path.join(TOP_DIR, 'third_party', 'libunwind')
  if not os.path.isdir(libunwind):
    process.Run(['git', 'clone', '--depth', '1' ,
                 'git://github.com/pathscale/libunwind.git'],
                cwd=os.path.join(TOP_DIR, 'third_party'), outfile=sys.stdout)


def main(argv):
  parser = argparse.ArgumentParser(add_help=False)
  parser.add_argument(
      '-v', '--verbose', dest='verbose',
      default=False, action='store_true',
      help='Produce more output.')

  parser.add_argument(
      '-c', '--clobber', dest='clobber',
      default=False, action='store_true',
      help='Clobber working directories before building.')

  parser.add_argument(
      '-p', '--skip-pnacl', dest='skip_pnacl',
      default=False, action='store_true',
      help='Skip pnacl build step.')

  parser.add_argument(
      '-s', '--skip-scons', dest='skip_scons',
      default=False, action='store_true',
      help='Skip scons build step.')

  parser.add_argument(
      '-o', '--output', dest='output',
      default=OUTPUT_ROOT,
      help='Set output dir.')

  parser.add_argument(
      '--no-cache', dest='no_cache',
      default=False, action='store_true',
      help='Do not use cached results.')

  options, leftover_args = parser.parse_known_args(argv)
  if '-h' in leftover_args or '--help' in leftover_args:
    print 'The following arguments are specific to toolchain_build_bionic.py:'
    parser.print_help()
    print 'The rest of the arguments are generic, in toolchain_main.py'
    return 1

  rebuild = False
  if options.clobber:
    print "Clobber Step"
    Rmdir(NACL_REPO_DIR)

  if not os.path.isfile(os.path.join(NACL_REPO_DIR, '.gclient')):
    print 'Fetching Native Client Repo from scratch.'
    Mkdir(NACL_REPO_DIR)
    # Fetch NaCl Repo
    process.Run(['fetch', 'nacl'], cwd=NACL_REPO_DIR)  
    rebuild = True

  # Verify Clang Tools are installed
  if not os.path.isfile(os.path.join(NACL_REPO_DIR, 'third_party', 'llvm-build')):
    process.Run(['python', 'tools/clang/scripts/update.py'], cwd=NACL_REPO_DIR)

  if rebuild or not options.skip_pnacl:
    BuildPNaCl(options)

  if rebuild or not options.skip_scons:
    BuildSCons(options)

  GetLibunwind()

if __name__ == '__main__':
  sys.exit(main(sys.argv))

